class TLVList

  attr_accessor :encoding, :entries, :length
  #
  #
  #
  def initialize(bs,encoding)
    @entries = Array.new();
    @encoding = encoding;

    if (encoding != TLV.DGI && encoding != TLV.EMV )
      raise(ArgumentError, "Invalid encoding", caller)
    end

    pb = ParseBuffer.new(bs.getBytes());

    while(pb.hasRemaining())
      len = 0;
      tag = 0;
      value = nil;
      case encoding
      when TLV.EMV
        tag = pb.getTag();              # Variable length type tag
        len = pb.getDERLength();        # DER length field
      when TLV.DGI
        tag = pb.getUnsignedWord();     # Two byte tag
        len = pb.getDGILength();        # DGI style length field
      end

      value = pb.get(len);
      tmp = TLV.new(tag,value,encoding);
      @entries.push(tmp);
    end
    @length = @entries.length;
  end

  #
  #
  #
  def index(index)
    return @entries[index]
  end

  #
  #
  #
  def find tag
    @entries.detect{ |tlv| tlv.getTag() == tag }
  end

  #
  #
  #
  def findAll tag
    @entries.find_all{ |tlv| tlv.getTag() == tag }
  end

  #
  #
  #
  def toByteString
    tmp = Array.new()
    @entries.each{ |tlv| tmp << tlv.getTLV().bs }
    tmp.flatten!
    return ByteString.new(tmp,HEX);
  end

  #
  #
  #
  def findIndex tag
    @entries.find_index{ |tlv| tlv.getTag() == tag }
  end
end